<?php
include 'includes/header.php';
require_once 'config/database.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

$database = new Database();
$db = $database->getConnection();

// Get user details
$user_query = "SELECT * FROM users WHERE id = ?";
$user_stmt = $db->prepare($user_query);
$user_stmt->execute([$_SESSION['user_id']]);
$user = $user_stmt->fetch();

// Get user's favorite cars
$favorites_query = "SELECT c.*, b.name as brand_name, m.name as model_name 
                   FROM favorites f 
                   JOIN cars c ON f.car_id = c.id 
                   LEFT JOIN brands b ON c.brand_id = b.id 
                   LEFT JOIN models m ON c.model_id = m.id 
                   WHERE f.user_id = ?";
$favorites_stmt = $db->prepare($favorites_query);
$favorites_stmt->execute([$_SESSION['user_id']]);
$favorite_cars = $favorites_stmt->fetchAll();

// Get user's inquiries
$inquiries_query = "SELECT i.*, c.title as car_title, c.main_image 
                    FROM inquiries i 
                    JOIN cars c ON i.car_id = c.id 
                    WHERE i.user_id = ? 
                    ORDER BY i.created_at DESC";
$inquiries_stmt = $db->prepare($inquiries_query);
$inquiries_stmt->execute([$_SESSION['user_id']]);
$inquiries = $inquiries_stmt->fetchAll();

// Get user's test drives
$test_drives_query = "SELECT t.*, c.title as car_title, c.main_image 
                      FROM test_drives t 
                      JOIN cars c ON t.car_id = c.id 
                      WHERE t.user_id = ? 
                      ORDER BY t.preferred_date DESC";
$test_drives_stmt = $db->prepare($test_drives_query);
$test_drives_stmt->execute([$_SESSION['user_id']]);
$test_drives = $test_drives_stmt->fetchAll();

// Handle profile update
if (isset($_POST['update_profile'])) {
    $username = sanitize_input($_POST['username']);
    $email = sanitize_input($_POST['email']);
    $first_name = sanitize_input($_POST['first_name']);
    $last_name = sanitize_input($_POST['last_name']);
    $phone = sanitize_input($_POST['phone']);

    // Check if username or email already exists
    $check_query = "SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?";
    $check_stmt = $db->prepare($check_query);
    $check_stmt->execute([$username, $email, $_SESSION['user_id']]);
    
    if ($check_stmt->rowCount() > 0) {
        set_message('Username or email already exists', 'danger');
    } else {
        $update_query = "UPDATE users SET username = ?, email = ?, first_name = ?, last_name = ?, phone = ? WHERE id = ?";
        $update_stmt = $db->prepare($update_query);
        
        if ($update_stmt->execute([$username, $email, $first_name, $last_name, $phone, $_SESSION['user_id']])) {
            set_message('Profile updated successfully');
            redirect('profile.php');
        } else {
            set_message('Error updating profile', 'danger');
        }
    }
}

// Handle password change
if (isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    if ($new_password !== $confirm_password) {
        set_message('New passwords do not match', 'danger');
    } elseif (password_verify($current_password, $user['password'])) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $update_query = "UPDATE users SET password = ? WHERE id = ?";
        $update_stmt = $db->prepare($update_query);
        
        if ($update_stmt->execute([$hashed_password, $_SESSION['user_id']])) {
            set_message('Password updated successfully');
            redirect('/profile.php');
        } else {
            set_message('Error updating password', 'danger');
        }
    } else {
        set_message('Current password is incorrect', 'danger');
    }
}
?>

<div class="container py-4">
    <div class="row">
        <!-- Profile Information -->
        <div class="col-md-4 mb-4">
            <div class="card shadow">
                <div class="card-body">
                    <h4 class="card-title mb-4">Profile Information</h4>
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" name="username" 
                                   value="<?php echo htmlspecialchars($user['username']); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" 
                                   value="<?php echo htmlspecialchars($user['email']); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">First Name</label>
                            <input type="text" class="form-control" name="first_name" 
                                   value="<?php echo htmlspecialchars($user['first_name']); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Last Name</label>
                            <input type="text" class="form-control" name="last_name" 
                                   value="<?php echo htmlspecialchars($user['last_name']); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="tel" class="form-control" name="phone" 
                                   value="<?php echo htmlspecialchars($user['phone']); ?>">
                        </div>
                        
                        <button type="submit" name="update_profile" class="btn btn-primary">Update Profile</button>
                        <?php if ($user['is_admin']): ?>
                            <a href="admin/index.php" class="btn btn-secondary">Admin Dashboard</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <!-- Change Password -->
            <div class="card shadow mt-4">
                <div class="card-body">
                    <h4 class="card-title mb-4">Change Password</h4>
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">Current Password</label>
                            <input type="password" class="form-control" name="current_password" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">New Password</label>
                            <input type="password" class="form-control" name="new_password" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Confirm New Password</label>
                            <input type="password" class="form-control" name="confirm_password" required>
                        </div>
                        
                        <button type="submit" name="change_password" class="btn btn-primary">Change Password</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Favorites and Activity -->
        <div class="col-md-8">
            <!-- Favorite Cars -->
            <div class="card shadow mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">Favorite Cars</h5>
                </div>
                <div class="card-body">
                    <div class="favorites-section">
                        <div class="row">
                            <?php foreach ($favorite_cars as $car): ?>
                                <div class="col-md-4 mb-4" id="favorite-card-<?php echo $car['id']; ?>">
                                    <div class="card h-100">
                                        <img src="<?php echo htmlspecialchars($car['main_image']); ?>" 
                                             class="card-img-top" 
                                             alt="<?php echo htmlspecialchars($car['title']); ?>"
                                             style="height: 200px; object-fit: cover;">
                                        <div class="card-body">
                                            <h5 class="card-title"><?php echo htmlspecialchars($car['title']); ?></h5>
                                            <p class="card-text">
                                                <?php echo htmlspecialchars($car['brand_name']); ?> /
                                                <?php echo htmlspecialchars($car['model_name']); ?><br>
                                                $<?php echo number_format($car['price'], 2); ?>
                                            </p>
                                            <div class="d-flex justify-content-between align-items-center">
                                                <a href="car-details.php?id=<?php echo $car['id']; ?>" 
                                                   class="btn btn-primary">Details</a>
                                                <button class="btn btn-outline-danger remove-favorite" 
                                                        data-car-id="<?php echo $car['id']; ?>">
                                                     Remove
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Activity -->
            <div class="card shadow">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs">
                        <li class="nav-item">
                            <a class="nav-link active" data-bs-toggle="tab" href="#inquiries">Inquiries</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" data-bs-toggle="tab" href="#test-drives">Test Drives</a>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <div class="tab-content">
                        <!-- Inquiries Tab -->
                        <div class="tab-pane fade show active" id="inquiries">
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Car</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Phone</th>
                                            <th>Message</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($inquiries as $inquiry): ?>
                                            <tr>
                                                <td><?php echo date('Y-m-d', strtotime($inquiry['created_at'])); ?></td>
                                                <td>
                                                    <a href="car-details.php?id=<?php echo $inquiry['car_id']; ?>">
                                                        <?php echo htmlspecialchars($inquiry['car_title']); ?>
                                                    </a>
                                                </td>
                                                <td><?php echo htmlspecialchars($inquiry['name']); ?></td>
                                                <td><?php echo htmlspecialchars($inquiry['email']); ?></td>
                                                <td><?php echo htmlspecialchars($inquiry['phone']); ?></td>
                                                <td><?php echo htmlspecialchars(substr($inquiry['message'], 0, 50)) . '...'; ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $inquiry['status'] == 'Pending' ? 'warning' : 'success'; ?>">
                                                        <?php echo $inquiry['status']; ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Test Drives Tab -->
                        <div class="tab-pane fade" id="test-drives">
                            <?php foreach ($test_drives as $test_drive): ?>
                                <div class="d-flex mb-3 p-3 bg-light rounded">
                                    <img src="/<?php echo htmlspecialchars($test_drive['main_image']); ?>" 
                                         alt="Car" style="width: 100px; height: 60px; object-fit: cover;">
                                    <div class="ms-3">
                                        <h6><?php echo htmlspecialchars($test_drive['car_title']); ?></h6>
                                        <p class="mb-1">
                                            Scheduled for: <?php echo date('M d, Y', strtotime($test_drive['preferred_date'])); ?>
                                            at <?php echo date('h:i A', strtotime($test_drive['preferred_time'])); ?>
                                        </p>
                                        <small class="text-muted">
                                            Status: <span class="badge bg-<?php 
                                                echo $test_drive['status'] === 'Pending' ? 'warning' : 
                                                    ($test_drive['status'] === 'Approved' ? 'success' : 
                                                    ($test_drive['status'] === 'Completed' ? 'info' : 'danger')); 
                                            ?>"><?php echo $test_drive['status']; ?></span>
                                        </small>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.remove-favorite').forEach(button => {
    button.addEventListener('click', function() {
        const carId = this.dataset.carId;
        const card = document.getElementById('favorite-card-' + carId);
        
        if (confirm('Are you sure you want to remove this car from favorites?')) {
            fetch('ajax/toggle_favorite.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'car_id=' + carId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Animate the removal of the card
                    card.style.transition = 'all 0.3s ease';
                    card.style.opacity = '0';
                    card.style.transform = 'scale(0.8)';
                    setTimeout(() => {
                        card.remove();
                        // If no more favorites, show a message
                        if (document.querySelectorAll('.remove-favorite').length === 0) {
                            document.querySelector('.favorites-section').innerHTML = 
                                '<h3>My Favorites</h3><p class="text-muted">You have no favorite cars yet.</p>';
                        }
                    }, 300);
                } else {
                    alert(data.message || 'Error removing from favorites');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error removing from favorites');
            });
        }
    });
});
</script>

<?php include 'includes/footer.php'; ?> 